from marshmallow import Schema,fields,validate,ValidationError,post_load,post_dump,validates,validates_schema
from application.apps.users.models import User,UserProfile
from flask import jsonify

class UserProfileSchema(Schema):
	education = fields.Integer()
	middle_school = fields.String()

class UserSchema(Schema):
	name = fields.String()
	age = fields.Integer()
	email = fields.Email()
	money = fields.Number()
	info = fields.Nested(UserProfileSchema,only=["middle_school"])
	class Meta:
		fields = ['name','age','money','email','info']
		ordered = True # 转换成有序字典

class UserSchema2(Schema):
	name = fields.String()
	sex = fields.Integer(validate=validate.OneOf([0,1,2]))
	age = fields.Integer(missing=18)
	email = fields.Email()
	mobile = fields.String()
	password = fields.String(load_only=True) # 设置当前字段为只写字段,只会在反序列化阶段启用

	@post_load
	def post_load(self,data,**kwargs):
		return User(**data)

	@post_dump
	def post_dump(self,data,**kwargs):
		data['mobile'] = data['mobile'][:3] + "*****" + data["mobile"][-3:]
		return data

class UserSchema3(Schema):
	name = fields.String(required=True)
	sex = fields.String(required=True,error_messages={"required":"对不起,permission必须填写"})
	age = fields.Integer(missing=18,validate=validate.Range(min=18,max=40,error="年龄必须在18-40之间"))
	email = fields.Email(error_messages={"invalid":"对不起,必须填写邮箱格式"})
	mobile = fields.String(required=True,validate=validate.Regexp("^1[3-9]\d{9}$",error="手机号格式不正确"),error_messages={"Regexp":"手机格式不正确"})

	@post_load
	def make_user_obj(self,data,**kwargs):
		return User(**data)

class UserSchema4(Schema):
	name = fields.String(required=True)
	sex = fields.String(required=True,error_messages={"required":"对不起,permission必须填写"})
	age = fields.Integer(missing=18,validate=validate.Range(min=18,max=40,error="年龄必须在18-40之间"))
	email = fields.Email(error_messages={"invalid":"对不起,必须填写邮箱格式"})
	mobile = fields.String(required=True,validate=validate.Regexp("^1[3-9]\d{9}$",error="手机号格式不正确"),error_messages={"Regexp":"手机格式不正确"})
	password = fields.String(required=True,load_only=True)
	password2 = fields.String(required=True,allow_none=True)

	@post_load
	def make_user_obj(self,data,**kwargs):
		return User(**data)

	@validates("name")
	def validate_name(self,data,**kwargs):
		print("name=%s" % data)
		if data == "root":
			raise ValidationError({"对不起,root用户是超级用户!您没有权限注册"})

		# 必须有返回值
		return data
	@validates_schema
	def validate(self,data,**kwargs):
		print(data)
		if data["password"] != data["password2"]:
			raise ValidationError("密码和确认密码必须一样")

		data.pop("password2")
		return data


def index():
	'''序列化'''
	# '''单个模型数据的序列化处理'''
	user1 = User(name="xiaoming",password="123456",age=16,email="333@qq.com",money=31.50)
	print(user1)
	# 把模型对象转换成字典格式

	data1 = UserSchema().dump(user1)
	print(type(data1),data1)
	# 把模型对象转换成json字符串格式
	data2 = UserSchema().dumps(user1)
	data = {"name":"yunchao"}
	# print(type(data2),data2)

	# '''多个模型数据的序列化'''
	# user1 = User(name="xiaoming",password="123456",age=15,email="333@wqq.com",money=31.50)
	# user2 = User(name="xiaohong", password="123456", age=16, email="333@qq.com", money=31.50)
	# user3 = User(name="xiaopang", password="123456", age=17, email="333@qq.com", money=31.50)
	# data_list = [user1,user2,user3]
	# data1 = UserSchema(many=True).dump(data_list)
	# print(type(data1),data1)

	# '''序列化嵌套使用'''
	# user1 = User(name="xiaoming",password="123456",age=15,email="333@qq.com", money=31.50)
	# user1.info = UserProfile(
	# 	education = 3,
	# 	middle_school = "北京师范学院附属中学白沙路分校"
	# )
	# data = UserSchema().dump(user1)
	# # print(data)
	# data = UserSchema().dumps(user1)
	# # print(type(data),data)

	# '''反序列化'''
	# user_data = {"name":"xiaoming","sex":"abc"}
	# us2 = UserSchema2()
	# result = us2.load(user_data,partial=True)
	# print(result)

	# user_data = {"name": "xiaoming", "password": "123456", "sex": 1}
	# us2 = UserSchema2()
	# result = us2.load(user_data)
	# print(result)

	# user_data = {"name": "xiaoming", "password": "123456", "sex": 1, "mobile": "133123454656"}
	# us2 = UserSchema2()
	#
	# result = us2.load(user_data)
	# print(result)
	#
	# us3 = UserSchema2(only=['sex','name','age','mobile']) #限制处理的字段
	# result2 = us3.dump(result)
	# print(result2)

	return data

def index3():
	# user_data = {"mobile":"13313456355","name": "xiaoming","age":24, "email": "xiaoming@qq.com","sex":"1"}
	# us3 = UserSchema3()
	# result = us3.load(user_data)
	# result2 = us3.dumps(result)
	# print(result)
	# print(result2)

	user_data = {"password":"123456","password2":"123456","mobile":"13313345635","name": "root1","age":40, "email": "xiaoming@qq.com","sex":"abc"}
	us4 = UserSchema4()
	result = us4.load(user_data)
	print(result)
	return 'ok'



